<?php
namespace common\fixtures;

use yii;
use yii\filters\auth\AuthMethod;

class HttpTokenAuth extends AuthMethod
{
    /**
     * @var string the parameter name for passing the access token
     */
    public $tokenParam = 'Token';

    /**
     * @inheritdoc
     */
    public function beforeAction($action)
    {
        $response = $this->response ? : Yii::$app->getResponse();
        try {
            $identity = $this->authenticate(
                $this->user ? : Yii::$app->getUser(),
                $this->request ? : Yii::$app->getRequest(),
                $response
            );
        } catch (yii\web\UnauthorizedHttpException $e) {
            return true;
        }
        return true;
    }


    /**
     * @inheritdoc
     */
    public function authenticate($user, $request, $response)
    {
        $accessToken = $this->getAccessToken($request);
        if (is_string($accessToken)) {
            $identity = $user->loginByAccessToken($accessToken, get_class($this));
            if ($identity !== null) {
                return $identity;
            }
        }
        Yii::$app->user->logout();
        return null;
    }


    /**
     * @inheritdoc
     */
    public function logout($request)
    {
        $accessToken = $this->getAccessToken($request);
        Yii::$app->user->logout();
        Yii::$app->cache->delete($accessToken);
    }

    /**
     * @param yii\web\Request $request
     * @return array|string
     */
    public function getAccessToken(yii\web\Request $request)
    {
        $data = array_merge($request->get(),$request->post());
        $accessToken = $request->headers->get($this->tokenParam);
        if(empty($accessToken)&&isset($data[$this->tokenParam])){
            $accessToken = $data[$this->tokenParam];
        }
        return $accessToken;
    }
}